#! /usr/bin/env python

import os, os.path
import sys
import stat
import shutil
from time import time

from optparse import OptionParser

from utils import build_redis

QUEUE = {
   'port':5210,
   'config_dir': '/opt/etc/queue',
   'data_dir' : '/opt/data/queue',
   'run_dir' : '/opt/var/run/queue',
   'log_dir' : '/opt/var/log/queue'
}
CACHE = {
    'port':6379,
    'config_dir' : '/opt/etc/attr',
    'data_dir' : '/opt/data/attr',
    'run_dir' : '/opt/var/run/attr',
    'log_dir' : '/opt/var/log/attr' 
}

def config(action, inst_num, max_mem, slaveof=None):
    if action == "attr":
        os.system("/opt/local/bin/redis_init attr %s %s" %(inst_num, max_mem))
    else:
        p = QUEUE['port']
        if slaveof is not None:
            for i in range(inst_num, 0, -1):
                port = p + i - 1
                os.system("/opt/local/bin/redis_init queue %s %s %s:%s" %(i, max_mem, slaveof, port))
        else:
            os.system("/opt/local/bin/redis_init queue %s %s" %(inst_num, max_mem))


USAGE = '''
    redis_install [options] install_type source_code_file instance_number memory_size [slaveof]

Description:
    Tool to install redis for queue or attribute cache.       

Arguments:
    install_type           - the install type, eithor 'queue' or 'attr'
    source_file            - the path of source code file.
    instance_number        - how many instance will be created.
    memory_size            - memory size for each instance.
    slaveof                - the ip address the master server, it's optional.

Example: 
    redis_install queue /opt/downloads/redis-xxx.tar.gz 3 10 vip-raid1
'''
    
def main():
    parser = OptionParser(version="1.6.2-SNAPSHOT")
    
    parser.usage = USAGE
    (options, args) = parser.parse_args()
    
    if len(args) < 4:
        parser.print_help()
        sys.exit(1)
 
    if os.system("/opt/local/bin/env_check.sh") != 0:
        sys.exit(1)
   
    action = args[0]
    srcfile = args[1]
    
    instance_num = int(args[2])
    max_mem = args[3]
    
    slaveof = None
    if len(args) > 4:
        slaveof = args[4]
    
    output_dir = "/opt/local/redis"
    redis_bin = os.path.join(output_dir, 'bin/redis-server') 
    # skip build
    if not os.path.isfile(redis_bin):
        build_redis(srcfile, output_dir)
    
    # make directories structure.
    if action == 'queue':
        cfg = QUEUE
    else:
        cfg = CACHE

    for d in cfg.keys():
        if d[-3:] == "dir" and  not os.path.isdir(cfg[d]) :
            print "create dir %s." % d
            os.makedirs(cfg[d])
       
    os.system("/opt/local/bin/bakup.sh /opt/etc/%s cnf"%action)
    config(action, instance_num, max_mem, slaveof)
    print "Install %s success." % action
    
if __name__ == '__main__':
    main()
    
